package com.example.oasystem.controller.address;

import com.example.oasystem.config.ConstantProperties;
import com.example.oasystem.dao.address.AoaDirectorDao;
import com.example.oasystem.dao.attachment.AoaAttachmentListDaoOfJian;
import com.example.oasystem.entity.address.AoaDirector;
import com.example.oasystem.entity.address.AoaDirectorUsers;
import com.example.oasystem.entity.address.OutShowDTO;
import com.example.oasystem.entity.attachment.AoaAttachmentListOfJian;
import com.example.oasystem.entity.daymanage.EmpDTO;
import com.example.oasystem.entity.page.Page;
import com.example.oasystem.entity.user.AoaUser;
import com.example.oasystem.service.impl.AddressServiceImpl;
import com.example.oasystem.utils.AliyunOSSUtil;
import com.example.oasystem.utils.PinYinUtil;
import com.github.pagehelper.PageInfo;
import org.apache.ibatis.annotations.Param;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpSession;
import java.io.File;
import java.io.FileOutputStream;
import java.text.SimpleDateFormat;
import java.util.*;

@Controller
public class addressController {
    @Autowired
    AddressServiceImpl addressService;
    @Autowired
    AoaDirectorDao directorDao;
    @Autowired
    private AliyunOSSUtil aliyunOSSUtil;
    @Autowired
    private ConstantProperties constantProperties;
    @Autowired
    private AoaAttachmentListDaoOfJian aoaAttachmentListDaoOfJian;
    private Set<Integer> checkboxs =new HashSet<>();
    //内部通讯录查找
    public void getAddrPageMethod(HttpSession session, Model model, int pageNum, int pageSize, String text, String baseKey){
        AoaUser user = (AoaUser) session.getAttribute("user");
        if (text == null || text.trim().equals("ALL")){
            text = "";
        }
        PageInfo<AoaUser> alls = addressService.getIndoorUserLimit(pageNum, pageSize, text,baseKey);
        Page page=new Page(alls.getSize(), Math.toIntExact(alls.getTotal()),alls.getPages(),alls.getPageNum(),alls.isIsFirstPage(),alls.isIsLastPage());
        List<AoaUser> users = alls.getList();
        List<String> catalogs = addressService.getCate(user.getUserId());
        int count=directorDao.selectNoHandle(user.getUserId());
        model.addAttribute("page",page);
        model.addAttribute("catalogs",catalogs);
        model.addAttribute("count",count);
        model.addAttribute("users",users);
        model.addAttribute("text",baseKey);
        model.addAttribute("url","getAddrPage");
    }
    //存疑！！！
    public void shareuserPaging(Model model,String text,int pageNum,int pageSize,HttpSession session){
        /*PageInfo<EmpDTO> all = addressService.getAllEmpsLimit(pageNum, pageSize, text);
        Page page=new Page(all.getSize(), Math.toIntExact(all.getTotal()),all.getPages(),all.getPageNum(),all.isIsFirstPage(),all.isIsLastPage());
       */
        AoaUser user=(AoaUser)session.getAttribute("user");
        List<EmpDTO> emps =directorDao.getAllEmps("",user.getUserId());

        /*List<EmpDTO> emps=all.getList();*/



        /*model.addAttribute("modalpage",page);*/
        model.addAttribute("users",emps);
        model.addAttribute("modalurl","shareuser");
        model.addAttribute("checkboxs",checkboxs);
    }
    //外部通讯录上下页
    public void goOutAddressPagingLimit(HttpSession session,Model model,int pageNum,int pageSize,String text,String baseKey,String outtype){
        AoaUser user = (AoaUser)session.getAttribute("user");
        if (text == null || text.trim().equals("ALL")){
            text = "";
        }
        PageInfo<AoaDirector> alls = addressService.getOutUserLimit(Math.toIntExact(user.getUserId()), text, pageNum, pageSize,outtype,baseKey);
        Page page=new Page(alls.getSize(), Math.toIntExact(alls.getTotal()),alls.getPages(),alls.getPageNum(),alls.isIsFirstPage(),alls.isIsLastPage());
        List<AoaDirector> directors = alls.getList();
        for (AoaDirector director : directors) {
            System.out.println(director);
        }
        List<String> catalogs = addressService.getCate(user.getUserId());

        model.addAttribute("page",page);
        model.addAttribute("catalogs",catalogs);
        model.addAttribute("directors",directors);
        model.addAttribute("text",baseKey);
        model.addAttribute("url","outaddresspaging");
        model.addAttribute("userId",user.getUserId());

    }
    //初次进入
    @RequestMapping("addrmanage")
    public String goAddrmanage(HttpSession session, Model model,
                               @RequestParam(value = "pageNum",defaultValue = "1")int pageNum,
                               @RequestParam(value = "baseKey",defaultValue = "")String baseKey,
                               @RequestParam(value = "pageSize",defaultValue = "10")int pageSize,
                               @RequestParam(value = "text",defaultValue = "")String text){

        getAddrPageMethod(session,model,pageNum,pageSize,text,baseKey);
        return "address/addrmanage";
    }
    //分页
        @RequestMapping("getAddrPage")
    public String getAddrPage(HttpSession session, Model model,
                              @RequestParam(value = "pageNum",defaultValue = "1")int pageNum,
                              @RequestParam(value = "baseKey",defaultValue = "")String baseKey,
                              @RequestParam(value = "pageSize",defaultValue = "10")int pageSize,
                              @RequestParam(value = "text",defaultValue = "")String text){
        getAddrPageMethod(session,model,pageNum,pageSize,text,baseKey);
        return "address/inaddrss";
    }
    //内部通讯录
    @RequestMapping("inaddresspaging")
    public String goInaddRessPaging( @RequestParam(value = "alph",defaultValue = "")String text,
                                     @RequestParam(value = "baseKey",defaultValue = "")String baseKey,
                                     HttpSession session, Model model,
                                     @RequestParam(value = "pageNum",defaultValue = "1")int pageNum,
                                     @RequestParam(value = "pageSize",defaultValue = "10")int pageSize){
        getAddrPageMethod(session,model,pageNum,pageSize,text,baseKey);
        return "address/inaddrss";
    }
    //外部通讯录
    @RequestMapping("outaddresspaging")
    public String goOutAddressPaging(HttpSession session,Model model,
                                     @RequestParam(value = "alph",defaultValue = "")String text,
                                     @RequestParam(value = "baseKey",defaultValue = "")String baseKey,
                                     @Param("outtype") String outtype,
                                     @RequestParam(value = "pageNum",defaultValue = "1")int pageNum,
                                     @RequestParam(value = "pageSize",defaultValue = "10")int pageSize){
        System.out.println("进了外部的分页");
        System.out.println("outtype = " + outtype);
        model.addAttribute("outtype",outtype);
        shareuserPaging(model,"",pageNum,pageSize,session);
        goOutAddressPagingLimit(session,model,pageNum,pageSize,text,outtype,baseKey);
        return "address/outaddrss";
    }
    @RequestMapping("shareuser")
    public String shareuser(Model model,@RequestParam(value = "baseKey",defaultValue = "")String text,
                            @RequestParam(value = "page",defaultValue = "1")int pageNum,
                            @RequestParam(value = "pageSize",defaultValue = "10")int pageSize,
                            HttpSession session){
        shareuserPaging(model,text,pageNum,pageSize,session);
        return "address/shareuser";

    }
    //内部通讯录查看
    @RequestMapping("inmessshow")
    public String goInMessShow(Model model,@Param("userId")Integer userId){
        AoaUser in = directorDao.findIn(userId);
        model.addAttribute("user",in);
        return "address/inmessshow";
    }
    //外部通讯录查看
    @RequestMapping("outmessshow")
    public String goOutMessShow(Model model,@Param("director")Integer director){
        OutShowDTO d = directorDao.findOut(director);
        model.addAttribute("d",d);
        return "address/outmessshow";
    }
    //新增外部分类
    @RequestMapping("addtypename")
    public String AddTypeName(@Param("typename")String typename,HttpSession session,Model model,
                              @Param("oldtypename")String oldtypename,
                              @RequestParam(value = "baseKey",defaultValue = "")String baseKey,
                              @RequestParam(value = "pageNum",defaultValue = "1")int pageNum,
                              @RequestParam(value = "pageSize",defaultValue = "10")int pageSize,
                              @RequestParam(value = "text",defaultValue = "")String text){
        AoaUser user = (AoaUser)session.getAttribute("user");
        if (oldtypename!=null && !("").equals(oldtypename.trim())){
            directorDao.updateOutTypeName(oldtypename,typename,user.getUserId());
        }else{
            directorDao.AddOutTypeName(user.getUserId(),typename);
        }
        getAddrPageMethod(session,model,pageNum,pageSize,text,baseKey);
        return "address/addtypename";
    }
    //删除外部分类
    @RequestMapping("deletetypename")
    public void DeleteTypeName(HttpSession session,Model model,@Param("typename")String typename){
        AoaUser user = (AoaUser)session.getAttribute("user");
        directorDao.deleteOutTypeName(user.getUserId(),typename);
    }
    //我共享的
    @RequestMapping("mesharemess")
    public String getMeShareMess(HttpSession session,Model model,
                                 @RequestParam(value = "text",defaultValue = "")String text,
                                 @RequestParam(value = "pageNum",defaultValue = "1")int pageNum,
                                 @RequestParam(value = "pageSize",defaultValue = "6")int pageSize){
        AoaUser user = (AoaUser)session.getAttribute("user");
        PageInfo<AoaDirector> alls = addressService.getMeShareMessLimit(user.getUserId(), pageNum, pageSize, text);
        Page page=new Page(alls.getSize(), Math.toIntExact(alls.getTotal()),alls.getPages(),alls.getPageNum(),alls.isIsFirstPage(),alls.isIsLastPage());
        List<AoaDirector> list = alls.getList();

        model.addAttribute("page",page);
        model.addAttribute("dus",list);
        model.addAttribute("text",text);
        model.addAttribute("url","mesharemess");
        return "address/mesharemess";
    }
    //共享与我
    @RequestMapping("sharemess")
    public String goShareMess(HttpSession session,Model model,
                              @RequestParam(value = "text",defaultValue = "")String text,
                              @RequestParam(value = "pageNum",defaultValue = "1")int pageNum,
                              @RequestParam(value = "pageSize",defaultValue = "3")int pageSize,
                              @RequestParam(value = "catalog",defaultValue = "")String catalog,
                              @RequestParam(value = "duid",defaultValue = "-1")int duid){
        if (duid !=-1){
            if ("外部通讯录".equals(catalog)){
                catalog = "";
            }
            directorDao.updateShareMess(catalog,duid);
        }
        AoaUser user = (AoaUser)session.getAttribute("user");
        PageInfo<AoaDirector> alls = addressService.getShareMeMess(user.getUserId(), pageNum, pageSize, text);
        Page page=new Page(alls.getSize(), Math.toIntExact(alls.getTotal()),alls.getPages(),alls.getPageNum(),alls.isIsFirstPage(),alls.isIsLastPage());
        List<AoaDirector> list = alls.getList();
        List<String> catalogs = addressService.getCate(user.getUserId());

        model.addAttribute("catalogs",catalogs);
        model.addAttribute("page",page);
        model.addAttribute("dus",list);
        model.addAttribute("text",text);
        model.addAttribute("url","sharemess");
        return "address/sharemess";
    }
    //新增、修改联系人
    @RequestMapping("addaddress")
    public String goAddAddress(HttpSession session,Model model,
                               @RequestParam(value = "did",defaultValue = "-1")int did){
        AoaUser user = (AoaUser)session.getAttribute("user");
        if (did != -1){
            AoaDirector director = directorDao.findDirector(did);
            model.addAttribute("director",director);
        }
        List<String> catalogs = directorDao.getCate(user.getUserId());
        model.addAttribute("calogs",catalogs);
        model.addAttribute("did",did);
        return "address/addressedit";
    }
    //保存新增或修改联系人
    @RequestMapping("savaaddress")
    public String saveAddress(Model model, MultipartFile filePath, AoaDirector director, HttpSession session,
                              @RequestParam(value = "text",defaultValue = "")String text,
                              @RequestParam(value = "baseKey",defaultValue = "")String baseKey,
                              @RequestParam(value = "pageNum",defaultValue = "1")int pageNum,
                              @RequestParam(value = "pageSize",defaultValue = "10")int pageSize,
                              @RequestParam(value = "catalogName",defaultValue = "")String catalogName){
        AoaUser user = (AoaUser) session.getAttribute("user");
        //这里是填入图片地址
        String uploadUrl =null;
        AoaAttachmentListOfJian aoaAttachmentListOfJian = new AoaAttachmentListOfJian();

        //这里的意思是图片有上传
        if (filePath!=null&&filePath.getSize()!=0) {
            uploadUrl = uploadFile(filePath, uploadUrl);
            aoaAttachmentListOfJian.setAttachmentPath(uploadUrl);
            String s = uploadUrl.split("\\?")[0];
            int beginIndex = s.lastIndexOf("/");
            String attachmentName = s.substring(beginIndex + 1);
            String attachmentShuffix = attachmentName.split("\\.")[1];
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

            aoaAttachmentListOfJian.setModel("aoa_director");
            aoaAttachmentListOfJian.setUserId(user.getUserId() + "");
            aoaAttachmentListOfJian.setUploadTime(sdf.format(new Date()));
            aoaAttachmentListOfJian.setAttachmentShuffix(attachmentShuffix);
            aoaAttachmentListOfJian.setAttachmentName(filePath.getOriginalFilename());
            aoaAttachmentListOfJian.setAttachmentType(filePath.getContentType());
            aoaAttachmentListOfJian.setAttachmentSize(filePath.getSize() + "");
            aoaAttachmentListDaoOfJian.insert(aoaAttachmentListOfJian);
            director.setImagePath(String.valueOf(aoaAttachmentListOfJian.getAttachmentId()));
        }
        /*else
        {
            uploadUrl="";
        }*/
        /*director.setImagePath(uploadUrl);*/
        director.setUserId(user.getUserId());
        String s = PinYinUtil.getPinyin(director.getUserName());
        director.setPinyin(s);
        System.out.println(director);
        if (director.getDirectorId()== -1){
            //添加并返回自增主键
            Long directorId = addressService.addDirector(director);
            directorDao.addDirectorUser(directorId,user.getUserId(),catalogName);
        }else{
            if (filePath!=null&&filePath.getSize()==0) {
                int pathid=directorDao.selectPathId(director.getDirectorId());
                director.setImagePath(String.valueOf(pathid));
            }
            directorDao.updateDirectorUser(director,director.getDirectorId());
            directorDao.updateDirector(catalogName,user.getUserId(),director.getDirectorId());
        }
        getAddrPageMethod(session,model,pageNum,pageSize,text,baseKey);

        return "address/addrmanage";
    }
    public String uploadFile(MultipartFile filePath, String uploadUrl) {
        try {
            if(null != filePath){
                String filename = filePath.getOriginalFilename();
                if(!"".equals(filename.trim())){
                    File newFile = new File(filename);
                    FileOutputStream os = new FileOutputStream(newFile);
                    os.write(filePath.getBytes());
                    os.close();
                    filePath.transferTo(newFile);
                    //上传到OSS
                    uploadUrl = constantProperties.getHead() + aliyunOSSUtil.upload(newFile) + constantProperties.getEnd();
                }
            }
        }catch (Exception ex) {
            ex.printStackTrace();
        }
        return uploadUrl;
    }
    //分享联系人
    @RequestMapping("shareother")
    public String shareother(Model model,HttpSession session,@RequestParam(value = "directors[]") int[] directors,@RequestParam(value = "sharedirector")int sharedirector){
        AoaUser user = (AoaUser) session.getAttribute("user");
        ArrayList<Integer> integers = addressService.shareUser(checkboxs, Math.toIntExact(user.getUserId()), sharedirector);
        List<EmpDTO> list = new ArrayList<>();
        checkboxs.removeAll(checkboxs);
        if (integers.size()>0){
            for (Integer integer:integers){
                list.add(directorDao.getEmpsById(integer));
            }
            model.addAttribute("users",list);
            return "address/userhas";
        }

        return "address/sharesuccess";
    }
    @ResponseBody
    @RequestMapping("checkBox")
    public void checkBox(@RequestParam(value = "checkbox[]") ArrayList<Integer> checkbox,
                         @RequestParam(value = "notcheckbox[]") ArrayList<Integer> notcheckbox){
        checkboxs.addAll(checkbox);
        Iterator<Integer> iterator = checkboxs.iterator();
        while (iterator.hasNext()){
            Integer next = iterator.next();
            for (int i:notcheckbox){
                if (next == i){
                    iterator.remove();
                    break;
                }
            }
        }
    }
    @ResponseBody
    @RequestMapping("changethistype")
    public String changethistype(@RequestParam(value = "did",defaultValue = "-1")int did,
                                 HttpSession session,@RequestParam(value = "catalog",defaultValue = "")String catalog){
        AoaUser user = (AoaUser) session.getAttribute("user");
        if ("外部通讯录".equals(catalog)){
            catalog = "";
        }
        directorDao.updateDirector(catalog,user.getUserId(), Long.valueOf(did));
        return "success";
    }
    @RequestMapping("deletedirector")
    public String deletedirector(@RequestParam(value = "did",defaultValue = "-1")int did,Model model){

        directorDao.deletedirectorUser(did);

        return "redirect:outaddresspaging";
    }
}
